<?php
namespace app\api\controller;


use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use think\Exception;

class AliyunSMS{
    private $client;
    public function __construct($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret,
        ]);
        $config->endpoint = "dysmsapi.aliyuncs.com";
        $this->client = new Dysmsapi($config);
    }

    public function sendSMS($phoneNumbers, $signName, $templateCode, $templateParam = [])
    {
        try {
            $sendSmsRequest = new SendSmsRequest([
                "phoneNumbers" => $phoneNumbers,
                "signName" => $signName,
                "templateCode" => $templateCode,
                "templateParam" => !empty($templateParam) ? json_encode($templateParam) : null
            ]);

            $runtime = new \AlibabaCloud\Dara\Models\RuntimeOptions();
            $response = $this->client->sendSmsWithOptions($sendSmsRequest, $runtime);

            return [
                'success' => $response->body->code === 'OK',
                'code' => $response->body->code,
                'message' => $response->body->message,
                'bizId' => $response->body->bizId,
                'requestId' => $response->body->requestId
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'code' => 'Exception',
                'message' => $e->getMessage()
            ];
        }
    }

    public function sendVerificationCode($phone, $code)
    {
        $templateParam = [
            'code' => $code
        ];

        return $this->sendSMS(
            $phone,
            '阿里云短信测试', // 短信签名
            'SMS_327311465', // 模板CODE
            $templateParam
        );
    }
}